// 2025/3/16
// https://leetcode.cn/problems/flatten-binary-tree-to-linked-list/description/?envType=study-plan-v2&envId=top-100-liked
// 二叉树展开为链表

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
    public:
        void flatten(TreeNode* root) {
            if(root == nullptr) return;
            TreeNode* cur = root, *left = root->left, *right = root->right;
            while(cur)
            {
                if(cur->left)
                {
                    left = cur->left;
                    right = cur->right;
                    cur->right = left;
                    while(left->right) left = left->right;
                    left->right = right;
                }
                cur->left = nullptr;
                cur = cur->right;
            }
        }
    };